package com.dap.batch.controller;

import com.dap.batch.constant.BatchConstant;
import com.dap.batch.dao.IDaoService;
import com.dap.batch.entity.Result;
import com.dap.batch.enums.ResultEnum;
import com.dap.batch.exception.BatchCustomException;
import com.dap.batch.po.BatchGroupExecutionPo;
import com.dap.batch.service.IBatchGroupService;
import com.dap.batch.utils.ResultUtils;
import com.dap.dao.model.QueryResult;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2017/9/28 15:59
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/9/28 15:59
 */
@RestController
@RequestMapping("/v1/group")
public class BatchGroupMonitorController {

    private final static Logger logger = LoggerFactory.getLogger(BatchGroupMonitorController.class);

    private IDaoService daoService;
    private IBatchGroupService groupService;

    @Autowired
    public BatchGroupMonitorController(IDaoService daoService, IBatchGroupService groupService) {
        this.daoService = daoService;
        this.groupService = groupService;
    }

    /**
     * 查询所有监控数据
     *
     * @param po
     * @param page
     * @param limit
     * @return
     */
    @ApiOperation(value = "获取任务组监控信息", httpMethod = "GET")
    @GetMapping("/monitors")
    public Result list(BatchGroupExecutionPo po
            , @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit) {
        if (po == null) {
            po = new BatchGroupExecutionPo();
        }
        String name = po.getGroupName();
        Short status = po.getStatus();
        String catalog = po.getCatalog();
        Long id = po.getId();
        if (StringUtils.isEmpty(catalog)) {
            po.setCatalog(null);
        }
        if (StringUtils.isEmpty(status)) {
            po.setStatus(null);
        }
        if (StringUtils.isEmpty(id)) {
            po.setId(null);
        }
        if (!StringUtils.isEmpty(name)) {
            StringBuffer sb = new StringBuffer("%");
            sb.append(name).append("%");
            po.setGroupName(sb.toString());
        } else {
            po.setGroupName(null);
        }
        String mapper = BatchGroupExecutionPo.class.getName() + BatchConstant.SELECT_LIKE;
        QueryResult<BatchGroupExecutionPo> result = daoService.selectQueryResult(mapper, po,
                page, limit);
        if (result.getTotalrecord() == 0) {
            throw new BatchCustomException(ResultEnum.NOT_FOUND);
        }
        return ResultUtils.success(result);
    }

    /**
     * 修改参数
     * @param po
     * @return
     */
    @ApiOperation(value = "修改任务组监控执行参数", httpMethod = "PUT")
    @PutMapping("/monitor")
    public Result update(BatchGroupExecutionPo po) {
        int i = daoService.update(po);
        if (i == 0) {
            throw new BatchCustomException(ResultEnum.NOT_FOUND);
        }
        return ResultUtils.success(ResultEnum.CREATED);
    }

    /**
     * 续跑操作
     * @param exeId
     * @return
     */
    @ApiOperation(value = "续跑任务组", httpMethod = "POST")
    @PostMapping("/goon/{exeId}")
    public Result goon(@PathVariable Long exeId) {
        try {
            groupService.goon(exeId);
            return ResultUtils.success(ResultEnum.CREATED);
        } catch (Exception e) {
            logger.error("续跑失败", e);
            throw new BatchCustomException(ResultEnum.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 重跑操作
     * @param exeId
     * @return
     */
    @ApiOperation(value = "重跑任务组", httpMethod = "POST")
    @PostMapping("/redo/{exeId}")
    public Result redo(@PathVariable Long exeId) {
        try {
            groupService.redo(exeId);
            return ResultUtils.success(ResultEnum.CREATED);
        } catch (Exception e) {
            logger.error("重跑失败", e);
            throw new BatchCustomException(ResultEnum.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 停止操作
     * @param exeId
     * @param force 是否强制执行 1:强制 0:不强制
     * @return
     */
    @ApiOperation(value = "停止任务组", httpMethod = "POST")
    @PostMapping("/cancel/{exeId}")
    public Result cancel(@PathVariable Long exeId,@RequestParam Integer force) {
        try {
            groupService.cancel(exeId, false, force==1);
            return ResultUtils.success(ResultEnum.CREATED);
        } catch (Exception e) {
            logger.error("停止失败", e);
            throw new BatchCustomException(ResultEnum.INTERNAL_SERVER_ERROR);
        }
    }
}
